import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Input, DatePicker, Popconfirm, FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getWorkerServiceList,
  createPatientArchive,
  updatePatientArchive,
  updateWorkerOrderStatus,
} from '@/services/order/api';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import { OptType, ServiceType } from '@/utils/constants';
import { showMsg, MsgType, isSupportSticky, currentDate, getDateValue, isNull, isExits, isScroll } from '@/utils/utils';
import OptForm from './OptForm';
import { ProFormFieldSet, ModalForm } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import { formatDate, parseDate, getCache, setCache } from '@/utils/utils';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import TableHint from '@/components/TableHint/Index';
import moment from 'moment';
import ChoicePatient from '@/components/ChoicePatient/list';

type WorkerServiceItem = {
  order_id?: string;
  patient_name?: string;
  identity_no?: string;
  nurse_day?: number;
  service_type?: string;
  service_content?: string;
  total_recom_price?: string;
  total_service_price?: string;
  order_status?: string;
  channel?: string;
  create_date?: string;
  create_time?: string;
};

type WorkerServiceItemList = {
  record_list?: WorkerServiceItem[];
  sum_record_num?: number;
};

interface OrderWorkerServiceListProps {
  location?: any;
}

const OrderWorkerServiceList: React.FC<OrderWorkerServiceListProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const [waitHandleNum, setWaitHandleNum] = useState<number>(0);
  const [clickSearch, setClickSearch] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const [inputNo, setInputNo] = useState(''); // 身份证/病案号

  const [clickRow, setClickRow] = useState(query?.order_id || ''); // 当前选中的行编号，用于定位颜色

  // 查看已预约接口参数
  const [reseverParams, setReseverParams] = useState<any>({});

  const [curHgInfo, setCurHgInfo] = useState([]);

  // 按表单筛选项查询
  const forFormSearch = () => {
    setClickSearch(true);
    setReseverParams({});
    formRef.current?.submit();
  }

  const columns: ProColumns<WorkerServiceItem>[] = [
    {
      title: '姓名',
      dataIndex: 'patient_name',
      search: false,
      width: 60,
    },
    {
      title: '下单日期',
      dataIndex: 'create_date',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <ProFormFieldSet style={{ gap: 2 }}>
            <DatePicker allowClear={false} style={{ width: '100%' }} />
            <span style={{ padding: '0 5px' }}>-</span>
            <DatePicker allowClear={false} style={{ width: '100%' }} />
          </ProFormFieldSet>
        );
      },
    },
    {
      title: '身份证/病案号',
      dataIndex: 'input_no',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ChoicePatient
            caseNoKey={initialState?.canAll ? 'out_case_no' : 'case_no'}
            showMore
            onChoice={(e) => setInputNo(e.visit_no)}
          />
        );
      },
    },
    {
      title: '身份证号/住院号',
      dataIndex: 'identity_no',
      search: false,
      width: 150,
      render: (val, record) => {
        return record.admission_num || record.identity_no;
      }
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入患者姓名" />
        );
      },
    },
    {
      title: '服务方式',
      dataIndex: 'service_type',
      width: 60,
      search: false,
      render: (_, record: WorkerServiceItem) => {
        return ServiceType[record.service_type as string];
      },
    },
    {
      title: '服务内容',
      dataIndex: 'service_content',
      search: false,
      width: 60,
      valueType: 'select',
      valueEnum: {
        P: '陪诊',
        H: '护理',
      },
    },
    {
      title: '护工信息',
      dataIndex: 'worker_list',
      search: false,
      width: 120,
      render: (val, record) => isNull(val) ? '-' : <div>{val[0].worker_no}-{val[0].worker_name}<EllipsisOutlined onClick={() => {
        val.forEach(element => {
          if (element.is_check === 'N') {
            element.end_time = null;
            element.check_day = null;
          }
        });
        setCurHgInfo(val)
      }} className='handClick' style={{ fontSize: 16 }} /></div>
    },
    {
      title: '档案编号',
      dataIndex: 'order_id',
      search: false,
      width: isScroll ? 120 : 165,
    },
    {
      title: '订单创建时间',
      search: false,
      width: isScroll ? 85 : 140,
      renderText: (_, record) => {
        return record.create_date + ' ' + record.create_time;
      },
    },
    {
      title: '下单渠道',
      dataIndex: 'channel',
      valueType: 'select',
      width: 60,
      valueEnum: {
        H: '院内',
        M: '小程序',
      },
    },
    {
      title: '服务费汇总',
      dataIndex: 'total_service_price',
      valueType: 'money',
      align: 'right',
      search: false,
    },
    {
      title: '介绍费汇总',
      dataIndex: 'total_recom_price',
      valueType: 'money',
      align: 'right',
      search: false,
      width: 70,
    },

    {
      title: '订单状态',
      dataIndex: 'order_status',
      // fixed: 'right',
      // fixed: isSupportSticky() ? 'right' : '',
      valueType: 'select',
      valueEnum: {
        C: '已预约',
        P: '已派单',
        E: '已作废',
        F: '已结单',
      },
      align: 'center',
      width: isScroll ? 60 : 80,
    },
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      // fixed: isSupportSticky() ? 'right' : '',
      width: 110,
      align: 'center',
      render: (_, record: WorkerServiceItem) => {
        // 订单状态 C：已预约，P：已派单，F：已结单, E: 已作废
        const { order_status, service_num } = record;

        if (order_status === 'P') {
          return [
            isExits('400403002') &&
            <a
              key="view"
              onClick={() => {
                history.push({
                  pathname: `/order/worker/patient/archiveInfo`,
                  query: {
                    order_id: record.order_id as string,
                  },
                });
              }}
            >
              查看/编辑
            </a>,

            (service_num > 0 && isExits('400403005')) && (
              <Popconfirm
                placement="topRight"
                key="settle"
                onConfirm={async () => {
                  const success = await updateOrderStatus(record, 'F');
                  if (success) {
                    showMsg('已结单', MsgType.SUCCESS);
                    actionRef.current?.reload();
                  }
                }}
                title="结单后，该档案记录将无法修改，是否继续？"
                okText="确认结单"
                cancelText="再想想"
              >
                <a>结单</a>
              </Popconfirm>
            ),
          ];
        }

        if ((order_status === 'F' || order_status === 'E') && isExits('400403004')) {
          return [
            <a
              key="view"
              onClick={() => {
                history.push({
                  pathname: `/order/worker/patient/archiveInfo`,
                  query: {
                    order_id: record.order_id as string,
                  },
                });
              }}
            >
              查看
            </a>,
          ];
        }

        return [
          isExits('400403002') && <a
            key="view"
            onClick={() => {
              history.push({
                pathname: `/order/worker/patient/archiveInfo`,
                query: {
                  order_id: record.order_id as string,
                },
              });
            }}
          >
            查看/编辑
          </a>,

          (!service_num && isExits('400403003')) && (
            <a
              key="drop"
              onClick={async () => {
                const success = await updateOrderStatus(record, 'E');
                if (success) {
                  showMsg('已作废', MsgType.SUCCESS);
                  actionRef.current?.reload();
                }
              }}
            >
              作废
            </a>
          ),
        ];
      },
    },
  ];
  

  /**
   * 创建
   * @param fields
   */
  const handleAdd = async (fields: WorkerServiceItem) => {
    try {
      let data = null;
      if (optType === OptType.ADD) {
        data = await createPatientArchive({ ...fields });
      } else {
        data = await updatePatientArchive({ ...fields });
      }
      showMsg(optType === OptType.ADD ? '添加成功' : '修改成功', MsgType.SUCCESS);
      return data;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return null;
    }
  };

  /**
   * 更改订单状态
   * @param record
   */
  const updateOrderStatus = async (record: WorkerServiceItem, status: string) => {
    try {
      const params = {
        order_id: record.order_id as string,
        status,
      };
      await updateWorkerOrderStatus(params);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };

  useEffect(() => {
    if (query?.from !== 'detail') {
      setCache('worker_service', '');
      formRef.current?.setFieldsValue({
        create_date: [moment().startOf('month'), '', currentDate()],
      });
      
      formRef.current?.submit();
      return;
    }
    let searchCondition = getCache('worker_service');
    searchCondition = JSON.parse(searchCondition || '{}');

    // 点击预约列表查看详情返回
    if (searchCondition.isReserve) {
      setReseverParams({
        order_status: 'C'
      })
    }

    console.log('当月', moment().startOf('month'));

    formRef.current?.setFieldsValue({
      create_date: [
        searchCondition.begin_create_date
          ? parseDate(searchCondition.begin_create_date)
          : moment().startOf('month'),
        '',
        searchCondition.end_create_date
          ? parseDate(searchCondition.end_create_date)
          : currentDate(),
      ],
      no: searchCondition.no,
      patient_name: searchCondition.patient_name,
      channel: searchCondition.channel,
      order_status: searchCondition.isReserve ? null : searchCondition.order_status,
    });
    formRef.current?.submit();
  }, []);

  // 点击查看
  const onView = () => {
    if (formRef.current) {
      setReseverParams({
        order_status: 'C'
      });
      formRef.current.submit();
    }
  };


  const columns1 = [
    {
      title: '护工编号',
      dataIndex: 'worker_no',
    },
    {
      title: '护工姓名',
      dataIndex: 'worker_name',
    },
    {
      title: '服务开始时间',
      dataIndex: 'begin_time',
    },
    {
      title: '服务结束时间',
      dataIndex: 'end_time',
    },
    {
      title: '服务天数',
      dataIndex: 'check_day',
      align: 'right',
    },
  ]
  
  return (
    <PageContainer extra={[<BreadcrumbDept />]} className="order-worker-container" breadcrumb={{}}>
      <ProTable<WorkerServiceItem, WorkerServiceItem & { create_date?: any[] } & COMMON.PageParams>
        rowKey="order_id"
        actionRef={actionRef}
        bordered
        className="worker-pro-table"
        formRef={formRef}
        manualRequest={true}
        request={async (params) => {
          console.log(params);
          const { create_date } = params;
          const extra = {
            begin_create_date: null,
            end_create_date: null,
          };
          if (create_date && create_date.length) {
            extra.begin_create_date =
              (create_date[0] && formatDate(create_date[0], 'YYYYMMDD')) || '';
            extra.end_create_date =
              (create_date[2] && formatDate(create_date[2], 'YYYYMMDD')) || '';
          }

          params.no = inputNo;
          params = { ...params, ...extra };

          delete params.create_date;
          if (create_date && create_date[0] && create_date[2]) {
            if (getDateValue(moment(create_date[0]).format('YYYY-MM-DD')) > getDateValue(moment(create_date[2]).format('YYYY-MM-DD'))) {
              showMsg('下单结束时间不能早于开始时间', MsgType.INFO);
              return {
                data: [],
                success: true,
                total: 0,
              };
            }
          }

          const searchCondition = {};

          if (reseverParams.order_status) {
            params = {
              current: params.current,
              pageSize: params.pageSize,
              order_status: reseverParams.order_status,
              isReserve: 1
            }
          }
          for (const prop in params) {
            if (!['current', 'pageSize'].includes(prop)) {
              searchCondition[prop] = params[prop];
            }
          }
          setCache('worker_service', JSON.stringify(searchCondition));
          console.log('params111', params, reseverParams)
          try {
            const data: WorkerServiceItemList = await getWorkerServiceList(params);
            setWaitHandleNum(data.sub_num);

            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num,
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0,
            };
          }
        }}
        search={{
          span: 8,
          labelWidth: 120,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            return [
              <PermissionControl key="search" action_id="400403000">
                <Button type="primary" onClick={() => {
                  forFormSearch()
                }}>查询</Button>
              </PermissionControl>
            ];
          },
        }}
        options={false}
        toolBarRender={() => [
          <div>
            <PermissionControl key="add" action_id="400403001">
              <Button
                onClick={() => {
                  setVisible(true);
                  setOptType(OptType.ADD);
                }}
                icon={<PlusOutlined />}
                type="primary"
              >
                患者服务档案
              </Button>
            </PermissionControl>
            <div>
              { waitHandleNum > 0 && (
                <TableHint
                  key="tablehint"
                  text={
                    <div>
                      有 <span style={{ color: '#F2232C', fontWeight: 'bold' }}>{waitHandleNum}</span>{' '}
                      条预约记录，请及时处理。
                    </div>
                  }
                  onAction={() => {
                    onView();
                  }}
                  showAction
                />
              )}
            </div>
          </div>,
        ]}
        // scroll={{ x: 1150 }}
        columns={columns}
        pagination={{
          showQuickJumper: true,
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.order_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.order_id === clickRow ? 'tableRowClick' : ''
        }}
      />

      {visible && (
        <OptForm
          handleAdd={handleAdd}
          actionRef={actionRef}
          optType={optType}
          handleModalVisible={setVisible}
        />
      )}
      {
        !isNull(curHgInfo) &&
        <ModalForm
          title="护工信息"
          visible
          modalProps={{
            maskClosable: false,
            onCancel: () => setCurHgInfo([])
            
          }}
          submitter={false}
        >
        <ProTable
          bordered
          className="worker-pro-table"
          manualRequest={true}
          columns={columns1}
          dataSource={curHgInfo}
          search={false}
          options={false}
          pagination={false}
        />
        </ModalForm>
      }
    </PageContainer>
  );
};

export default OrderWorkerServiceList;
